package utils;

import book.PairOfUidAndBookId;
import com.bit.utils.FileUtils;

import java.io.IOException;


public class AnalyzingBorrowedBook {

    public void storeObject(PairOfUidAndBookId[] pairOfUidAndBookIds , String filename) throws IOException {
        int bookUseLen = 0;
        for (int i = 0; i < pairOfUidAndBookIds.length; i++) {
            if(pairOfUidAndBookIds[i] != null){
                bookUseLen++;
            }
        }

        StringBuilder jsonArray = new StringBuilder();

        for (int i = 0; i < bookUseLen; i++) {
            if(pairOfUidAndBookIds[i] != null){
                jsonArray.append(pairOfUidAndBookIds[i].toJson());
            }
            if(i != bookUseLen-1){
                jsonArray.append("\n");
            }
        }
        FileUtils.writeFile(jsonArray.toString(),filename);
    }

    public PairOfUidAndBookId[] loadObject(String filename) throws IOException{

        String content = FileUtils.readFile(filename);

        if(content == null || content.isEmpty()){
            System.out.println("已借阅书籍列表⽆数据，表⽰没有⽤⼾借阅过书籍");
            return null;
        }
        String[] JsonStrings = content.split("\n");
        PairOfUidAndBookId[] pairOfUidAndBookIds = new PairOfUidAndBookId[JsonStrings.length];

        for (int i = 0; i < JsonStrings.length; i++) {
            PairOfUidAndBookId pairOfUidAndBookId = new PairOfUidAndBookId();
            String[] uidAndBookIds = JsonStrings[i].split(",");
            pairOfUidAndBookId.setUserID(Integer.parseInt(uidAndBookIds[0]));
            pairOfUidAndBookId.setBookID(Integer.parseInt(uidAndBookIds[1]));
            pairOfUidAndBookIds[i] = pairOfUidAndBookId;

        }
        return pairOfUidAndBookIds;

    }
    //如果是多用户，我们需要再在loadObject中添加一个user ID的参数因为我们还需要再遍历一次JsonStrings，然后if(userID == 1)
    // if(userID == 2)我们会加载不同的数据到内存中

}
